#include "sessionfrienditem.h"
#include "mainwidget.h"
#include "model/datacenter.h"
SessionFriendItem::SessionFriendItem(QWidget *owner, const QIcon &avatar, const QString &name, const QString &lastMessage) : owner(owner)
{
    //基本属性设置
    selected = false;
    this->setStyleSheet("QWidget {background-color:rgb(230,230,230);}");
    this->setFixedHeight(60);

    //创建布局管理器
    layout = new QGridLayout();
    layout->setContentsMargins(10,0,10,0);
    layout->setHorizontalSpacing(10);
    layout->setVerticalSpacing(0);
    this->setLayout(layout);

    //创建头像图标
    QPushButton* userAvatar = new QPushButton();
    userAvatar->setFixedSize(40,40);
    userAvatar->setIconSize(QSize(40,40));
    userAvatar->setIcon(avatar);
    userAvatar->setStyleSheet("QPushButton{background-color: rgb(230,230,230); border:none;}");
    userAvatar->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);

    //创建昵称
    QLabel* userName = new QLabel();
    userName->setFixedHeight(20);
    userName->setText(name);
    userName->setStyleSheet("QLabel{font-size: 18px; font-weight: 100; }");
    userName->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);

    //创建文本内容
    messageLabel = new QLabel();
    messageLabel->setFixedHeight(20);
    messageLabel->setText(lastMessage);
    messageLabel->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);

    //添加到布局管理器中
    layout->addWidget(userAvatar,0,0,2,2);
    layout->addWidget(userName,0,2,1,8);
    layout->addWidget(messageLabel,1,2,1,8);
}

void SessionFriendItem::select()
{
    //更改所有同类元素的selected状态与样式
    const QObjectList& children = this->parentWidget()->children();
    //为什么owner不可以??
    //const QObjectList& children = this->owner->children();

    for(QObject* child : children)
    {
        if(!child->isWidgetType()) continue;

        SessionFriendItem* widget = dynamic_cast<SessionFriendItem*>(child);

        widget->setStyleSheet("QWidget {background-color:rgb(230,230,230);}");
        widget->selected = false;
    }

    //仅更改自身
    this->setStyleSheet("QWidget {background-color:rgb(203,200,198);}");
    this->selected = true;

    this->active();
}
/////////////////////////////////////////////////////////////
///事件重写
/////////////////////////////////////////////////////////////
void SessionFriendItem::mousePressEvent(QMouseEvent *event)
{
    LOG() << "void SessionFriendItem::mousePressEvent(QMouseEvent *event)";
    (void)event;
    select();

}

void SessionFriendItem::enterEvent(QEnterEvent *event)
{
    if(!selected) this->setStyleSheet("QWidget {background-color:rgb(218,218,218);}");
}

void SessionFriendItem::leaveEvent(QEvent *event)
{
    if(!selected) this->setStyleSheet("QWidget {background-color:rgb(230,230,230);}");
}

void SessionFriendItem::paintEvent(QPaintEvent *event)
{
    // 这⾥是官⽅⽂档给出的要求. 原因在⽂档上没有解释.
    (void) event;
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
/////////////////////////////////////////////////////////////
///不同业务处理的衍生Item类
/////////////////////////////////////////////////////////////
SessionItem::SessionItem(QWidget *owner, const QString &chatSessionId, const QIcon &avatar, const QString &name, const QString &lastMessage)
    :SessionFriendItem(owner,avatar,name,lastMessage), chatSessionId(chatSessionId),text(lastMessage) //
{
    DataCenter* dataCenter = DataCenter::getInstance();
    connect(dataCenter,&DataCenter::updateLastMessage,this,&SessionItem::updateLastMessage);

    //获取未读数目
    int unread = dataCenter->getUnread(chatSessionId);
    if(unread > 0)
    {
        messageLabel->setText(QString("[未读%1条]").arg(unread) + text);
    }
}

void SessionItem::active()
{
    MainWidget* mainWidget = MainWidget::getInstance();
    mainWidget->loadRecentMessage(chatSessionId);

    DataCenter* dataCenter = DataCenter::getInstance();
    dataCenter->clearUnread(chatSessionId);
    //重新设置文本
    messageLabel->setText(text);
}

void SessionItem::updateLastMessage(const QString& chatSessionId)
{
    if(this->chatSessionId != chatSessionId) return;

    //被筛选出的一定是需要添加更改的item, 获取最后一条消息
    DataCenter* dataCenter = DataCenter::getInstance();
    QList<Message>* messageList = dataCenter->getRecentMessages(chatSessionId);
    if (messageList == nullptr || messageList->size() == 0) {
        // 当前会话没有任何消息, 无需更新
        return;
    }
    const Message& lastMessage = messageList->back();

    //设置item的最后一条消息
    QString text = "";

    switch(lastMessage.messageType)
    {
    case model::MessageType::TEXT_TYPE:
        text = lastMessage.messageContent;
        break;
    case model::MessageType::FILE_TYPE:
        text = "[文件]";
        break;
    case model::MessageType::SPEECH_TYPE:
        text = "[语音]";
        break;
    case model::MessageType::IMAGE_TYPE:
        text = "[图片]";
        break;
    default:
        LOG() << "SessionItem::SessionItem 设置最后一条消息文本失败: 未知消息类型";
        break;
    }
    //显示内容, 需要先查看当前会话是否被选中, 选中则不更新未读, 未选中则做出前缀拼接

    if(chatSessionId == dataCenter->getCurrentChatSessionId())
    {
        messageLabel->setText(text);
    }
    else
    {
        int unread = dataCenter->getUnread(chatSessionId);
        if(unread > 0)
        {
            messageLabel->setText(QString("[未读%1条]").arg(unread) + text);
        }
    }

}

FriendItem::FriendItem(QWidget *owner, const QString &userId, const QIcon &avatar, const QString &name, const QString &description)
    :SessionFriendItem(owner,avatar,name,description), userId(userId)
{
}

void FriendItem::active()
{
    MainWidget* mainWidget = MainWidget::getInstance();
    mainWidget->switchSession(userId);
}

ApplyItem::ApplyItem(QWidget *owner, const QString &userId, const QIcon &avatar, const QString &name)
    :SessionFriendItem(owner,avatar,name,""), userId(userId)
{
    //过后释放
    layout->removeWidget(messageLabel);
    messageLabel->deleteLater();

    //创建按钮
    QPushButton* yesBtn = new QPushButton();
    yesBtn->setText("同意");

    QPushButton* noBtn = new QPushButton();
    noBtn->setText("拒绝");

    // layout->addWidget(messageLabel, 1, 2, 1, 8);
    layout->addWidget(yesBtn,1,2,1,4);
    layout->addWidget(noBtn,1,6,1,4);

    //////////////////////////////////////////////////////////////////////
    /// 添加同意按钮的信号槽
    /// //////////////////////////////////////////////////////////////////
    connect(yesBtn,&QPushButton::clicked,this,&ApplyItem::acceptFriendApply);
    connect(noBtn,&QPushButton::clicked,this,&ApplyItem::rejectFriendApply);
}

void ApplyItem::active()
{
    LOG()<<"void FriendItem::active() 尚未实现";
}

void ApplyItem::acceptFriendApply()
{
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    connect(dataCenter,&model::DataCenter::acceptFriendApplyDone,this,&ApplyItem::acceptFriendDone,Qt::UniqueConnection);
    dataCenter->acceptFriendApplyAsync(userId);
}

void ApplyItem::acceptFriendDone(const QString& userId)
{
    if(this->userId != userId)
    {
        return;
    }

    this->parentWidget()->layout()->removeWidget(this);

    Toast::showMessage("您已添加用户id为: " + userId + "的用户为好友!");

    this->deleteLater();
}

void ApplyItem::rejectFriendApply()
{
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    connect(dataCenter,&model::DataCenter::rejectFriendApplyDone,this,&ApplyItem::rejectFriendDone,Qt::UniqueConnection);
    dataCenter->rejectFriendApplyAsync(userId);
}

void ApplyItem::rejectFriendDone(const QString &userId)
{
    if(this->userId != userId)
    {
        return;
    }

    this->parentWidget()->layout()->removeWidget(this);

    Toast::showMessage("您已拒绝与用户id为: " + userId + "的用户成为好友");

    this->deleteLater();
}





























